import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../controllers/play_list_controller.dart';
import '../../entity/play_list_enity.dart';

class PlaylistPage extends StatelessWidget {
  final PlayListController controller = Get.put(PlayListController());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('播放列表'),
      ),
      body: Obx(() {
        // 使用 ReorderableListView 实现长按排序
        return ReorderableListView(
          onReorder: (oldIndex, newIndex) {
            // 默认播放列表不参与排序，忽略第一个
            if (oldIndex == 0 || newIndex == 0) return;

            controller.reorderPlaylists(oldIndex, newIndex);
          },
          children: List.generate(controller.playlists.length, (index) {
            final playlist = controller.playlists[index];

            return ListTile(
              key: ValueKey(playlist.id),
              leading: Icon(Icons.folder),
              // 文件夹图标
              title: Text(playlist.name),
              // 播放列表名称
              subtitle: Text('视频数量: ${playlist.videoIds?.length ?? 0}'),
              // 视频数量
              trailing: playlist.id == -1
                  ? null
                  : PopupMenuButton<String>(
                      onSelected: (value) {
                        if (value == 'edit') {
                          _showEditPlaylistDialog(context, playlist);
                        } else if (value == 'delete') {
                          _showDeleteConfirmationDialog(context, playlist.id);
                        }
                      },
                      itemBuilder: (context) => [
                        const PopupMenuItem(
                          value: 'edit',
                          child: Text('编辑'),
                        ),
                        const PopupMenuItem(
                          value: 'delete',
                          child: Text('删除'),
                        ),
                      ],
                    ),
              onTap: () {
                // TODO: 这里添加点击事件逻辑，例如跳转到视频列表页面
              },
            );
          }),
        );
      }),
      floatingActionButton: FloatingActionButton(
        onPressed: () => _showAddPlaylistDialog(context),
        child: Icon(Icons.add),
      ),
    );
  }

  // 显示添加播放列表的对话框
  void _showAddPlaylistDialog(BuildContext context) {
    final TextEditingController textController = TextEditingController();

    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('添加播放列表'),
          content: TextField(
            controller: textController,
            decoration: InputDecoration(hintText: '输入播放列表名称'),
          ),
          actions: <Widget>[
            TextButton(
              child: Text('取消'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
            TextButton(
              child: Text('添加'),
              onPressed: () async {
                final newName = textController.text.trim();
                if (newName.isNotEmpty) {
                  final success = await controller.addPlaylist(newName);
                  if (success) {
                    Navigator.of(context).pop(); // 关闭对话框
                  } else {
                    // 显示错误消息
                    ScaffoldMessenger.of(context).showSnackBar(
                      SnackBar(content: Text('播放列表名称已存在')),
                    );
                  }
                }
              },
            ),
          ],
        );
      },
    );
  }

  // 显示编辑播放列表的对话框
  void _showEditPlaylistDialog(BuildContext context, PlayListEntity playlist) {
    final TextEditingController textController = TextEditingController(text: playlist.name);

    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('编辑播放列表'),
          content: TextField(
            controller: textController,
            decoration: InputDecoration(hintText: '输入新的播放列表名称'),
          ),
          actions: <Widget>[
            TextButton(
              child: Text('取消'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
            TextButton(
              child: Text('保存'),
              onPressed: () async {
                final newName = textController.text.trim();
                if (newName.isNotEmpty) {
                  final success = await controller.updatePlaylistName(playlist.id, newName);
                  if (success) {
                    Navigator.of(context).pop(); // 关闭对话框
                  } else {
                    // 显示错误消息
                    ScaffoldMessenger.of(context).showSnackBar(
                      SnackBar(content: Text('播放列表名称已存在')),
                    );
                  }
                }
              },
            ),
          ],
        );
      },
    );
  }

  // 显示删除确认对话框
  void _showDeleteConfirmationDialog(BuildContext context, int playlistId) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('删除播放列表'),
          content: Text('确定要删除此播放列表吗？'),
          actions: <Widget>[
            TextButton(
              child: Text('取消'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
            TextButton(
              child: Text('删除'),
              onPressed: () async {
                await controller.deletePlaylist(playlistId);
                Navigator.of(context).pop(); // 关闭对话框
              },
            ),
          ],
        );
      },
    );
  }
}
